package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DefaultAsyncHttpClient;
import com.isunland.managesystem.entity.KnowledgeAnnounceList.KnowledgeAnnounceDetail;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.apache.http.Header;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员:  YuHao
 * 创建时间: 2016/5/4 15:19
 */
@SuppressWarnings("deprecation") public class PublishAccounceEditFragment
    extends PublishAnnounceBaseFragment {

  public static final String EXTRA_VALUE =
      "com.isunland.managesystem.ui.PublishAccounceEditFragment.EXTRA_VALUE";
  protected String mId;// 主键
  protected String mAnnounceType;// 公文类别
  protected String mAnnounceTypeCode;// 公文类别编码
  protected String mKeyWords;// 关键字
  protected String mTitle;// 标题
  protected String mFile;// 附件
  protected String mBeginDate;// 起始时间
  protected String mEndDate;// 结束时间
  protected String mContent;// 内容简介
  protected String mRemark;// 默认备注字段

  protected String mRegStaffName;// 创建人
  protected String mRegStaffId;// 创建人code
  protected String mRegDate;// 创建时间
  protected String mRegDepartment;// 创建部门
  protected String mRegDepartmentCode;// 创建部门code
  protected String mCheckStaffId;// 审核人ID
  protected String mCheckStaffName;// 审核人姓名
  protected String mCheckDate;// 审核日期

  protected String mOrderNo;// 默认排序字段
  protected String mMemberCode;// 会员编码
  protected String mMemberName;// 所属会员名称
  protected String mRunId;// 流程实例runId
  protected String mIfRemindReader;// 是否提示阅读人
  protected String mDocKnowledgeNo;// 公文编号
  protected String mDataStatus;// 数据状态
  protected String mSystemIndex;
  protected String mFileOriginalName;// 用户上传时设置的文件名称
  KnowledgeAnnounceDetail mDetail;
  private String mReadRangeName;
  private String mReadRangeFlag;

  public static Fragment newInstance(KnowledgeAnnounceDetail detail) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, detail);
    PublishAccounceEditFragment fragment = new PublishAccounceEditFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.announceEdit);
    mDetail = (KnowledgeAnnounceDetail) getArguments().getSerializable(EXTRA_VALUE);
    if (mDetail != null) {
      mId = mDetail.getId();
      mAnnounceType = mDetail.getDocKindName();
      mAnnounceTypeCode = mDetail.getDocKindCode();
      mKeyWords = mDetail.getDocKeyWords();
      mTitle = mDetail.getNoticeTitle();
      mFile = mDetail.getFilePath();
      mBeginDate = mDetail.getNoticeBegin();
      mEndDate = mDetail.getNoticeEnd();
      mContent = mDetail.getDocContentDesc();
      mRemark = mDetail.getRemark();// 默认备注字段

      mRegStaffName = mDetail.getRegStaffName();
      mRegStaffId = mDetail.getRegStaffId();
      mRegDate = mDetail.getRegDate();// 登记时间
      mRegDepartment = mDetail.getRegDeptName();
      mRegDepartmentCode = mDetail.getRegDeptCode();
      mCheckStaffId = mDetail.getCheckStaffId();// 审核人ID
      mCheckStaffName = mDetail.getCheckStaffName();// 审核人姓名
      mCheckDate = mDetail.getCheckDate();// 审核日期

      mOrderNo = mDetail.getOrderNo();// 默认排序字段
      mMemberCode = mDetail.getMemberCode();// 会员编码
      mMemberName = mDetail.getMemberName();
      mRunId = mDetail.getRunId();
      mIfRemindReader = mDetail.getIfRemindReader();
      mDocKnowledgeNo = mDetail.getDocKnowledgeNo();
      mDataStatus = mDetail.getDataStatus();
      mFileOriginalName = mDetail.getFileOriginalName();
      mSystemIndex = mDetail.getSystemIndex();
      mReadRangeName = mDetail.getReadRangeName();
      mReadRangeFlag = mDetail.getReadRangeFlag();
      LogUtil.i("mMemberName===" + mMemberName);
    }
  }

  protected void initView() {

    if (!TextUtils.isEmpty(mAnnounceType)) {
      mtvAnnounceTypePublicAnnounce.setTextContent(mAnnounceType);
    }

    if (!TextUtils.isEmpty(mKeyWords)) {
      mtvKeyWordsDetailPublicAnnounce.setTextContent(mKeyWords);
    }

    if (!TextUtils.isEmpty(mTitle)) {
      mtv_announceTitle.setTextContent(mTitle);
    }

    if (!TextUtils.isEmpty(mRemark)) {
      mtvOhtersRemark.setTextContent(mRemark);
    }

    //        if (!TextUtils.isEmpty(mBeginDate)) {
    //            mtv_beginDate.setTextContent(mBeginDate);
    //        }
    //
    //        if (!TextUtils.isEmpty(mEndDate)) {
    //            mtv_endDate.setTextContent(mEndDate);
    //        }

    if (!TextUtils.isEmpty(mFileOriginalName)) {
      if ("(null)".equalsIgnoreCase(mFileOriginalName)) {
        mtv_addFileAnnounce.setTextContent("");
      } else {
        mtv_addFileAnnounce.setTextContent(mFileOriginalName);
      }
    }

    if (!TextUtils.isEmpty(mRegStaffName)) {
      mtv_registerAnnounce.setTextContent(mRegStaffName);
    }
    if (!TextUtils.isEmpty(mRegDate)) {
      mtv_registerTimeAnnounce.setTextContent(mRegDate);
    }
    if (!TextUtils.isEmpty(mRegDepartment)) {
      mtv_registerDepartment.setTextContent(mRegDepartment);
    }

    mtv_announceIntroduction.setVisibility(View.VISIBLE);
    if (!TextUtils.isEmpty(mContent)) {
      mtv_announceIntroduction.setTextContent(mContent);
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override // 响应返回图标
  public boolean onOptionsItemSelected(MenuItem item) {
    AlertDialog.Builder dialog;
    switch (item.getItemId()) {

      case android.R.id.home:

        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      case R.id.menu_item_confirm:
        dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.restart_title);
        dialog.setMessage(R.string.ifSureSave);
        dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            volleyPostSave();
          }
        });

        dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
        dialog.create().show();
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 保存
   */
  private void volleyPostSave() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    String url = ApiConst.URL_SAVE_ANNOUNCE;
    RequestParams params = new RequestParams();
    params.put("type", "mobile");
    params.put("id", mId);

    if (TextUtils.isEmpty(mKnowledgeName)) {
      params.put("docKindName", mAnnounceType);// 公文类别
    } else {
      params.put("docKindName", mKnowledgeName);// 公文类别
    }

    if (TextUtils.isEmpty(mKnowledgeCode)) {
      params.put("docKindCode", mAnnounceTypeCode);// 公文类别编码
    } else {
      params.put("docKindCode", mKnowledgeCode);// 公文类别编码
    }
    params.put("docKeyWords", mtvKeyWordsDetailPublicAnnounce.getTextContent().trim());// 关键字
    params.put("noticeTitle", mtv_announceTitle.getTextContent().trim());// 公告标题
    params.put("ifRemindReader", "F");// 是否提示阅读人
    params.put("dataNoticeBegin", "");// 开始时间
    params.put("dataNoticeEnd", "");// 结束时间
    //        if (TextUtils.isEmpty(mStartTime)) {
    //            params.put("dataNoticeBegin", mBeginDate);// 开始时间
    //        } else {
    //            params.put("dataNoticeBegin", mStartTime);// 开始时间
    //        }
    //
    //        if (TextUtils.isEmpty(mEndTime)) {
    //            params.put("dataNoticeEnd", mEndDate);// 结束时间
    //        } else {
    //            params.put("dataNoticeEnd", mEndTime);// 结束时间
    //        }

    params.put("ckEditor", mtv_announceIntroduction.getTextContent().trim());// 公告内容
    if (!TextUtils.isEmpty(mtvOhtersRemark.getTextContent().trim())) {
      params.put("remark", mtvOhtersRemark.getTextContent().trim());// 备注
    }
    if (!TextUtils.isEmpty(mMemberCode)) {
      params.put("memberCode", mMemberCode);
    }

    if (!TextUtils.isEmpty(mDataStatus)) {
      params.put("dataStatus", mDataStatus);
    }
    if (!TextUtils.isEmpty(mRegStaffName)) {
      params.put("regStaffName", mRegStaffName);
    }

    if (!TextUtils.isEmpty(mReadRangeFlag)) {
      params.put("readRangeFlag", mReadRangeFlag);
    }
    if (!TextUtils.isEmpty(mRegDepartment)) {
      params.put("regDeptName", mRegDepartment);
    }
    if (!TextUtils.isEmpty(mRegStaffId)) {
      params.put("regStaffId", mRegStaffId);
    }
    if (!TextUtils.isEmpty(mRegDepartmentCode)) {
      params.put("regDeptCode", mRegDepartmentCode);
    }
    if (!TextUtils.isEmpty(mRunId)) {
      params.put("runId", mRunId);
    }
    if (!TextUtils.isEmpty(mSystemIndex)) {
      params.put("systemIndex", mSystemIndex);
    }
    if (!TextUtils.isEmpty(mCheckStaffName)) {
      params.put("checkStaffName", mCheckStaffName);
    }
    if (!TextUtils.isEmpty(mMemberName)) {
      params.put("memberName", mMemberName);
    }
    if (!TextUtils.isEmpty(mOrderNo)) {
      params.put("orderNo", mOrderNo);
    }
    if (!TextUtils.isEmpty(mDocKnowledgeNo)) {
      params.put("docKnowledgeNo", mDocKnowledgeNo);
    }
    if (!TextUtils.isEmpty(mCheckStaffId)) {
      params.put("checkStaffId", mCheckStaffId);
    }
    if (!TextUtils.isEmpty(mReadRangeName)) {
      params.put("readRangeName", mReadRangeName);
    }

    if (!TextUtils.isEmpty(mFile)) {
      params.put("filePath", mFile);
    }
    if (!TextUtils.isEmpty(mFileOriginalName)) {
      params.put("fileOriginalName", mFileOriginalName);
    }
    if (mFilePath != null) {
      InputStream myInputStream = null;
      try {
        myInputStream = new FileInputStream(mFilePath);
      } catch (FileNotFoundException e) {
        LogUtil.e("errorLog==", e);
        Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      }
      if (myInputStream != null) {
        String name = mFilePath.substring(mFilePath.lastIndexOf("/"), mFilePath.length());
        params.put("aFile", myInputStream, name);
      }
    }
    LogUtil.e("params===" + params);
    DefaultAsyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {

      @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
        try {
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(new String(arg2), SuccessMessage.class);
          String resutl = success.getResult();
          String message = success.getMessage();
          if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
            ToastUtil.show(message);
            MyUtils.dismissDialog();
            Intent intent = new Intent(getActivity(), PublishAccnouceListActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }

          if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
            MyUtils.show(getActivity(), message);
          }
        } catch (Exception e) {
          e.printStackTrace();
          MyUtils.show(getActivity(), R.string.save_failure);
        }
      }

      @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
        MyUtils.show(getActivity(), R.string.save_failure);
        LogUtil.e("arg0===" + arg0);
      }
    });
  }
}
